package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求提交的要下载的文件名
        String filename = request.getParameter("filename");
        //2. 创建输入流指向于 D:\\download\\ 下的指定的文件
        FileInputStream fis = new FileInputStream("D:\\download\\"+filename);
        //3. 设置 Content-Disposition
        // 响应头  如： resp.setHeader("Content-Disposition","attachment;filename=mysql-5.7.24-winx64.zip");
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        //4. 通过response对象获取输出流对象
        ServletOutputStream os = response.getOutputStream();
        //5. 读写数据
        int len;
        while ((len = fis.read())!=-1){
            os.write(len);
        }
        //6. 释放资源
        fis.close();
    }
}